package com.zhonghe.active4j.filesys.controller;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhonghe.active4j.common.controller.BaseController;
import com.zhonghe.active4j.core.annotation.Log;
import com.zhonghe.active4j.core.model.AjaxJson;
import com.zhonghe.active4j.core.model.LogType;
import com.zhonghe.active4j.core.model.PageInfo;
import com.zhonghe.active4j.core.query.QueryUtils;
import com.zhonghe.active4j.core.util.MyBeanUtils;
import com.zhonghe.active4j.core.util.ResponseUtil;
import com.zhonghe.active4j.core.util.ShiroUtils;
import com.zhonghe.active4j.filesys.entity.FileParserRuleEntity;
import com.zhonghe.active4j.filesys.service.FileParserRuleService;
import com.zhonghe.active4j.filesys.wrapper.FileParserRuleWrapper;

import lombok.extern.slf4j.Slf4j;
/**
 * 文件解析规则
 * @author gyj
 *
 */
@Controller
@RequestMapping("/filesys/fileparserrule")
@Slf4j
public class FileParserRuleController  extends BaseController{

	@Autowired
	private FileParserRuleService fileParserRuleService;
	
	/**
	 * 跳转到列表页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model) {
		return "filesys/fileparserrule/fileparserrule_list.html";
	}
	
	@RequestMapping("/listByParserId")
	public String list1(String parserId, Model model) {
		QueryWrapper<FileParserRuleEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("PARSER_ID", parserId);
		queryWrapper.orderByAsc("INDEX_CODE");//序号排序
		List<FileParserRuleEntity> listObjs = fileParserRuleService.list(queryWrapper);
		model.addAttribute("data", JSON.toJSONString(listObjs));
		return "filesys/fileparserrule/fileparserrule_d.html";
	}
	
	/**
	 *  获取表格数据 树形结构
	 * @param sysUserEntity
	 * @param request
	 * @return
	 */
	@RequestMapping("/datagrid")
	@ResponseBody
	public void datagrid(FileParserRuleEntity sysConfigEntity, PageInfo<FileParserRuleEntity> page, HttpServletRequest request, HttpServletResponse response) {
		//拼接查询条件
		QueryWrapper<FileParserRuleEntity> queryWrapper = QueryUtils.installQueryWrapper(sysConfigEntity, request.getParameterMap());
		
		//执行查询
		IPage<FileParserRuleEntity> lstResult = fileParserRuleService.page(page.getPageEntity(), queryWrapper);

		//结果处理,直接写到客户端
		ResponseUtil.write(response, new FileParserRuleWrapper(lstResult).wrap());
	}
	
	/**
	 * 跳转到页面
	 * @param sysDepartEntity
	 * @param model
	 * @return
	 */
	@RequestMapping("/add")
	public String add(FileParserRuleEntity sysConfigEntity, Model model) {
		model.addAttribute("isEdit", "NO");
		if(StringUtils.isNotEmpty(sysConfigEntity.getId())) {
			FileParserRuleEntity config = fileParserRuleService.getById(sysConfigEntity.getId());
			model.addAttribute("config", config);
			model.addAttribute("isEdit", "YES");
		}
		return "filesys/fileparserrule/fileparserrule.html";
	}
	
	/**
	 * 保存方法
	 * @param sysUserEntity
	 * @return
	 */
	@RequestMapping("/save")
	@RequiresPermissions("filesys/fileparserrule/add")
	@ResponseBody
	@Log(type = LogType.save, name = "保存用户信息", memo = "新增或编辑保存了用户信息")
	public AjaxJson save(FileParserRuleEntity sysConfigEntity, String roleIds)  {
		AjaxJson j = new AjaxJson();
		
		try{
			//后端校验
			if(StringUtils.isEmpty(sysConfigEntity.getCode())) {
				j.setSuccess(false);
				j.setMsg("编码不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getName())) {
				j.setSuccess(false);
				j.setMsg("名称不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getStatus())) {
				j.setSuccess(false);
				j.setMsg("状态不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getParserCode())) {
				j.setSuccess(false);
				j.setMsg("文件解析器编码不能为空");
				return j;
			}
			
			//新增保存
			if(StringUtils.isEmpty(sysConfigEntity.getId())) {
				
				fileParserRuleService.saveUser(sysConfigEntity, roleIds);
			}
			//编辑保存
			else {
				FileParserRuleEntity tmp = fileParserRuleService.getById(sysConfigEntity.getId());
				MyBeanUtils.copyBeanNotNull2Bean(sysConfigEntity, tmp);
				fileParserRuleService.saveOrUpdateUser(tmp, roleIds);
			}
			
		}catch(Exception e) {
			log.error("保存用户信息报错，错误信息:" + e.getMessage());
			j.setSuccess(false);
			e.printStackTrace();
		}
		
		return j;
	}
	
	/**
	 *  删除操作
	 * @param sysUserEntity
	 * @return
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("filesys:fileparserrule:delete")
	@ResponseBody
	@Log(type = LogType.del, name = "删除文件处理器", memo = "删除了文件处理器")
	public AjaxJson delete(FileParserRuleEntity sysConfigEntity) {
		AjaxJson j = new AjaxJson();
		try {
			
			if(StringUtils.isNotEmpty(sysConfigEntity.getId())) {
				String userId = ShiroUtils.getSessionUserId();
				if(StringUtils.equals(userId, sysConfigEntity.getId())) {
					j.setSuccess(false);
					j.setMsg("不允许删除自身账户");
					return j;
				}
				FileParserRuleEntity item = fileParserRuleService.getById(sysConfigEntity.getId());
				if(null != item && "1".equals(item.getStatus())) {
					j.setSuccess(false);
					j.setMsg("不允许删除非禁用的数据");
					return j;
				}
				fileParserRuleService.delete(sysConfigEntity);
			}
			
		}catch(Exception e) {
			log.error("删除文件处理器出错，错误信息:" + e.getMessage() );
			j.setSuccess(false);
			e.printStackTrace();
		}
		
		return j;
	}
	
	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping("batch/del")
	@ResponseBody
	@Log(type = LogType.del, name = "删除文件处理器", memo = "删除了文件处理器")
	public AjaxJson del(String ids) {
		AjaxJson j = new AjaxJson();
		try {
			//ids校验
			if(StringUtils.isEmpty(ids)) {
				j.setSuccess(false);
				j.setMsg("请选择一条记录");
			}
			//删除文件处理器
			Collection<FileParserRuleEntity> listByIds = fileParserRuleService.listByIds(Arrays.asList(ids));
			listByIds.forEach(e ->{
				String status = e.getStatus();
				if("1".equals(status)) {
					j.setSuccess(false);
					j.setMsg("存在启用的数据:【"+e.getCode()+"】");
				}
			});
			if(!j.isSuccess()) {
				return j;
			}
			fileParserRuleService.batchDels(ids);
		}catch(Exception e) {
			log.error("删除文件处理器报错，错误信息：{}", e.getMessage());
			j.setSuccess(false);
			e.printStackTrace();
		}
		return j;
	}
}
